var DBUtils = require("./mysqlManage");

/**
 * @param {Object} request
 * @param {Object} response
 * 传入参数：user{phone:...//电话号,password:...//密码}
 * 返回：data:{ type:...,//自定义状态码 msg:...,//描述信息 data:...//用户信息 } type:200 代表ok,201表示无此用户
 */
let userLogin = function(request,response){
    let data = request.body; 
    
    let sql = "select * from user where phone=? and password=?";
    let arr = [data.phone,data.password];//数组里存放的是传入的参数序列

    DBUtils.arrQuery(sql,arr,(data)=>{ 
		let userRes = data;
		let res;
		if(userRes.length == 1){ 
			res = { 
				type:200,
				msg:'ok',
				data:userRes
			}
		} else { 
			res = { 
				type:201,
				msg:'没有此用户',
				data:userRes
			}
		}
		console.log("user data = ",data)
        response.json(res);
    });
}

/**
 * @param {Object} request
 * @param {Object} response
 * 功能：用户注册
 * 传入参数：{ phone:...//电话号,password:....//设置的密码 }
 * 返回参数：{ type:...//自定义状态码,msg:...//描述信息 } //200 表示ok,201表示用户已注册,202表示注册异常
 */
let userRegister = function(request,response){ 
	let userData = request.body;
	
	//根据电话号码与密码查询是否存在该用户
	let sql = "select * from user where phone=? and password=?";
	let arr = [userData.phone,userData.password];//数组里存放的是传入的参数序列
	
	DBUtils.arrQuery(sql,arr,(loginData)=>{
		// let userRes = loginData;
		let res;
		//如果存在此用户
		if(loginData.length == 1){ 
			res = { 
				type:201,
				msg:'此用户已存在',
			}
			
			console.log("user data = ",loginData)
			response.json(res);
			return ;
		} else { 
			//添加此用户信息
			let insertSql = "insert user(phone,password) value(?,?)";
			let insertArr = [userData.phone,userData.password];//数组里存放的是传入的参数序列
			DBUtils.arrQuery(insertSql,insertArr,(registerData)=>{ 
				if(registerData.affectedRows == 1){ 
					res = {
						type:200,
						msg:'注册成功',
						data:registerData
					}
				}else { 
					res = {
						type:202,
						msg:'注册异常',
						data:registerData
					}
				}
				// console.log("注册成功 data",registerData);
				response.json(res);
				return ;
			})
		}
	});
}

module.exports.userRegister = userRegister;
module.exports.userLogin = userLogin;